<template>
  <div class="pui-switch">
    <div
      :class="['pui-switch_content', modelValue && 'is-checked', disabled && 'disabled', autofocus && 'autofocus']"
      @click="!disabled && handleClick()"
    >
      <span class="pui-switch_label m-r-10" :style="{ color: modelValue ? inactiveColor : activeColor }">{{ inactiveLabel }}</span>
      <span
        :class="['pui-switch_core', props.size]"
        :style="{ backgroundColor: modelValue ? activeColor : inactiveColor, borderColor: modelValue ? activeColor : inactiveColor }"
        ref="core"
      >
        <div class="autofocus" v-if="autofocus"></div>
        <span class="pui-switch_button">
          <pui-icon class="loading" name="loading" role v-if="loading"></pui-icon>
        </span>
      </span>
      <span class="pui-switch_label m-l-10" :style="{ color: modelValue ? activeColor : inactiveColor }">{{ activeLabel }}</span>
      <input type="checkbox" class="pui-switch_input" :checked="modelValue" :disabled="disabled" :name="name" ref="input" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'pui-switch',
});
</script>

<script lang="ts" setup>
import type { Props } from './interface.ts';

const emits = defineEmits<{
  (e: 'onChange', val: boolean): void;
  (e: 'update:modelValue', val: boolean): void;
}>();

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  size: 'normal',
  disabled: false,
  autofocus: false,
  isLoading: false,
  loading: false,
});

const handleClick = () => {
  emits('onChange', !props.modelValue);
  if (!props.isLoading) {
    emits('update:modelValue', !props.modelValue);
  }
};
</script>
